/* Copyright (c) 2010 Sven Weidauer
 
 Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files (the "Software"),to deal in the Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#include <Platform/Events.h>
#include <Platform/Threads.h>
#include <Platform/Atomics.h>

#include <stdio.h>
#include <unistd.h>

#ifdef WINDOWS
#   define sleep(x) usleep( (x) * 1000000 )
#include <Platform/Locks.h>
static MPLock __printfLock;
static void InitPrintfLock()
{
    MPCreateLock( &__printfLock );
}
#define printf(...) do { MPAquireLock( __printfLock ); printf(__VA_ARGS__); MPReleaseLock( __printfLock ); } while( 0 )
#else
#   define InitPrintfLock() ((void)0)
#endif

#define THREAD_COUNT 2

MPThread threads[THREAD_COUNT];

volatile MPWord runningThreads = 0;
volatile MPWord totalCreatedThreads = 0;

static void ThreadProc1( void *ud )
{
    MPAtomicIncrement( &runningThreads );
    MPAtomicIncrement( &totalCreatedThreads );
    
    unsigned long sleepTime = (750 + ((unsigned long long)rand() * 1500 / RAND_MAX));
    printf( "Thread %d running (sleeping for %ld ms)...\n", (int)ud, sleepTime );
    usleep( sleepTime * 1000 );
    printf( "Thread %d done...\n", (int)ud );
    
    MPAtomicDecrement( &runningThreads );
}

static void ThreadProc( void *ud )
{
    MPAtomicIncrement( &totalCreatedThreads );
    MPAtomicIncrement( &runningThreads );
    printf( "Main thread %d starting child threads...\n", (int)ud );
    MPThread level2threads[THREAD_COUNT];
    int startId = THREAD_COUNT * (int)ud;
    for (int i = 0; i < THREAD_COUNT; i++) {
        MPStartThread( &level2threads[i], ThreadProc1, (void *)( startId + i ) );
    }
    printf( "Main thread %d is waiting for the first child thread to terminate\n", (int)ud );
    MPWaitResult res = MPWaitForAnyEvent( THREAD_COUNT, level2threads, MP_TIMEOUT_FOREVER );
    if (MP_WAIT_EVENT_0 <= res && res < MP_WAIT_EVENT_0 + THREAD_COUNT) {
        printf( "Main thread %d: Child thread %d terminated first\n", (int) ud, startId + res - MP_WAIT_EVENT_0 );
    } else {
        printf( "Error waiting for first child thread to terminate\n" );
    }
    printf( "Main thread %d is waiting for all child threads to terminate\n", (int)ud );
    MPWaitForAllEvents( THREAD_COUNT, level2threads, MP_TIMEOUT_FOREVER );
    printf( "Main thread %d done...\n", (int)ud );
    
    MPAtomicDecrement( &runningThreads );
}

int main( int argc, char **argv )
{
    InitPrintfLock();
#ifndef WINDOWS
    sranddev();
#endif
    
    for (int i = 0; i < THREAD_COUNT; i++) {
        bool started = MPStartThread( &threads[i], ThreadProc, (void *)i );
        if (!started) {
            printf( "Error creating thread %d..\n", i );
            return 1;
        }
    }
    
    printf( "Waiting for threads to finnish (%d running)...\n", runningThreads );
    MPWaitResult res = MPWaitForAllEvents( THREAD_COUNT, threads, MP_TIMEOUT_FOREVER );
    if (res != MP_WAIT_FINNISHED) {
        const char *errstring = "unknown";
        switch (res) {
            case MP_WAIT_ERROR: errstring = "MP_WAIT_ERROR"; break;
            case MP_WAIT_SYSTEM_EVENT: errstring = "MP_WAIT_SYSTEM_EVENT"; break;
            case MP_WAIT_TIMEOUT: errstring = "MP_WAIT_TIMEOUT"; break;
        }
        printf( "Waiting returned an error: %d = %s\n", (int)res, errstring );
        return 2;
    }
    printf( "All threads done... (%d left)\n", runningThreads );
    printf( "Total created threads: %d\n", totalCreatedThreads );
    
    if (0 == runningThreads && totalCreatedThreads == (THREAD_COUNT * (THREAD_COUNT + 1))) {
        printf( "Test succeeded\n" );
    }
    
    return 0;
}